package chapter15;

import chapter15.generator.Coffee;
import chapter15.generator.Generator;
import chapter15.generator.Mocha;

import java.lang.reflect.InvocationTargetException;

/**
 * @author : DuJiabao
 * @Date : 2021/3/4 15:30
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
public class BasicGenerator<T> implements Generator<T> {
  private Class<T> type;

  public BasicGenerator(Class<T> type) {
    this.type = type;
  }

  @Override
  public T next() {
    try {
      return type.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> Generator<T> create(Class<T> type) {
    return new BasicGenerator<T>(type);
  }

  public static void main(String[] args) {
    Generator<Mocha> mochaGenerator = BasicGenerator.create(Mocha.class);
    for (int i = 0; i < 10; i++) {
      System.out.println(mochaGenerator.next());
    }
  }
}
